package com.dtwenty.gaming.client.widgets;

import com.dtwenty.gaming.client.widgets.D20Label.Position;
import com.dtwenty.gaming.data.FieldModifier;
import com.dtwenty.gaming.data.PlayerCharacter;
import com.dtwenty.gaming.data.PlayerCharacterFieldChangeEvent;
import com.dtwenty.gaming.data.PlayerCharacterFieldChangeHandler;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;

public class InitiativePanel extends CharacterSheetBox {
	private PlayerCharacter character = null;
	Integer halfLvl = 0; 
	Integer dex = 0;
	Integer misc = 0;
	private Label scoreLabel = new Label();
	private Label halfLvlLabel = new Label();
	private Label dexLabel = new Label();
	private Label miscLabel = new Label();

	InitiativePanel(PlayerCharacter character) {
		this.character = character;
		halfLvl = PlayerCharacter.calculateHalfLevel(character.getLevel());
		dex = PlayerCharacter.calculateAbilityModifier(character.getDexterity());
		calculateMisc();
		setup();
		setValues();
	}

	private void setup() {
		HorizontalPanel panel = new HorizontalPanel();
		panel.add(new D20Label("Score", scoreLabel, Position.TOP));
		panel.add(new D20Label("", new Label("Initiative"), Position.TOP));
		panel.add(new D20Label("DEX", dexLabel, Position.TOP));
		panel.add(new D20Label("1/2 LVL", halfLvlLabel, Position.TOP));
		panel.add(new D20Label("Misc.", miscLabel, Position.TOP));

		character.addPlayerCharacterFieldChangeHandler(new PlayerCharacterFieldChangeHandler() {
			public void onPlayerCharacterFieldChange(PlayerCharacterFieldChangeEvent event) {
				handleCharacterChange(event);
			}
		});

		setHeaderText("INITIATIVE");
		setBodyContent(panel);
	}

	private void setValues() {
		scoreLabel.setText(generateScore().toString());
		dexLabel.setText(dex.toString());
		halfLvlLabel.setText(halfLvl.toString());
		miscLabel.setText(misc.toString());
	}

	private Integer generateScore() {
		Integer score = new Integer(misc);
		score += dex;
		score += halfLvl;
		return score;
	}

	private void calculateMisc() {
		misc = 0;
//		for(FieldModifier fm : character.getFieldModifiers()) {
//			if(fm.getField() == PlayerCharacter.Field.INITIATIVE)
//				misc = (Integer)fm.modifyField(misc);
//		}
	}

	private void handleCharacterChange(PlayerCharacterFieldChangeEvent change) {
		switch (change.getFieldName()) {
		case LEVEL:
			halfLvl = PlayerCharacter.calculateHalfLevel(character.getLevel());
			halfLvlLabel.setText(halfLvl.toString());
			scoreLabel.setText(generateScore().toString());
			break;
		case DEXTERITY:
			dex = PlayerCharacter.calculateAbilityModifier(character.getDexterity());
			dexLabel.setText(dex.toString());
			scoreLabel.setText(generateScore().toString());
			break;
		case FIELD_MODIFIER:
			calculateMisc();
			miscLabel.setText(misc.toString());
			scoreLabel.setText(generateScore().toString());
			break;
		}
	}
}